package com.star.mianshidog.aop;

import com.star.mianshidog.annotation.DistributedLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * packageName com.star.mianshidog.annotation
 *
 * @author zerostart
 * @className DistributedLockAspect
 * @date 2024/10/1
 * @description
 */
@Aspect
@Component
public class DistributedLockAspect {


    @Resource
    private RedissonClient redissonClient;

    @Around("@annotation(distributedLock)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, DistributedLock distributedLock) {
        String lockKey = distributedLock.key();
        long leaseTime = distributedLock.leaseTime();
        long waitTime = distributedLock.waitTime();
        TimeUnit timeUnit = distributedLock.timeUnit();
        RLock lock = redissonClient.getLock(lockKey);
        boolean acquired = false;
        try {
            acquired = lock.tryLock(waitTime, leaseTime, timeUnit);
            if (acquired) {
                return proceedingJoinPoint.proceed();
            } else {
                throw new RuntimeException("获取锁失败");
            }
        } catch (Throwable e) {
            throw new RuntimeException("获取锁失败", e);
        }
        finally {
            if (acquired) {
                lock.unlock();
            }
        }
    }
}
